package com.example.notepad.diary

import android.os.Bundle
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
import com.example.notepad.R
import java.text.SimpleDateFormat
import java.util.Date

class DiaryListActivity : AppCompatActivity() {
    private lateinit var diaryListView: ListView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_diary_list)

        diaryListView = findViewById(R.id.diaryListView)

        // 从SharedPreferences加载日记列表
        val diaryEntries = loadDiaryEntries()

        // 将日记列表适配到ListView
        val adapter = DiaryAdapter(this, diaryEntries)
        diaryListView.adapter = adapter
    }

    override fun onBackPressed() {
        super.onBackPressed()
        finish() // 结束当前活动，这样返回时会回到MainActivity
    }

    private fun loadDiaryEntries(): List<DiaryEntry> {
        val sharedPreferences = getSharedPreferences("DiaryPrefs", MODE_PRIVATE)
        val entries = mutableListOf<DiaryEntry>()

        for (key in sharedPreferences.all.keys) {
            val diaryText = sharedPreferences.getString(key, "") ?: ""
            val savedTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(key) ?: Date()

            if (diaryText.isNotEmpty()) {
                entries.add(DiaryEntry(diaryText, savedTime))
            }
        }

        // 按时间降序排序
        entries.sortByDescending { it.savedTime }
        return entries
    }
}